﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BlackBox.Models
{
    public class GroupRepository
    {
        DataClassesDataContext db = new DataClassesDataContext();

        #region Singleton
        private static GroupRepository instance;

        public GroupRepository() { }

        public static GroupRepository Instance 
        {
            get
            {
                if (instance == null)
                    instance = new GroupRepository();
                return instance;
            }
        }
        #endregion

        #region Get All Groups
        public IEnumerable<Group> GetAllGroups()
		{
			var model = (from x in db.Groups
						 select x);
			return model;
		}
        #endregion 

        #region Get Group by ID
        public Group GetGroupById(int id)
        {
            Group myGroup = (from x in db.Groups
                          where x.id == id
                          select x).SingleOrDefault();

			return myGroup;
        }
        #endregion

        #region Get By Name
        public Group GetByName(string name)
		{
			Group myGroup = (from x in db.Groups
							 where x.name == name
							 select x).SingleOrDefault();
			return myGroup;
		}
        #endregion

        #region Get Groups By User
        public List<Group> GetGroupsByUser(int id)
		{
			var myGroupID = (from x in db.UserToGroups
							where x.UserID == id
							select x);

            //Converting to List
			List<Group> myGroups = new List<Group>();

			foreach(var newGroup in myGroupID)
			{
				Group temp = GetGroupById(newGroup.GroupID);
				myGroups.Add(temp);
			}

			return myGroups;
		}
        #endregion

        #region AddGroup
        public void AddGroup(Group newGroup)
		{
			db.Groups.InsertOnSubmit(newGroup);
			db.SubmitChanges();
		}
        #endregion

        #region Add Group Member
        public void AddGroupMember(int memberID, int groupID)
		{
			UserToGroup checkUser = (from x in db.UserToGroups
									 where x.UserID == memberID && x.GroupID == groupID
									 select x).SingleOrDefault();
            //If the Use is not allready  in the group we add him
			if (checkUser == null)
			{
				UserToGroup newMember = new UserToGroup
				{
					UserID = memberID,
					GroupID = groupID
				};

				db.UserToGroups.InsertOnSubmit(newMember);
				db.SubmitChanges();
			}
		}
        #endregion

        #region Remove Group Member
        public void RemoveGroupMember(int memberID, int groupID)
		{
			UserToGroup myUser = (from x in db.UserToGroups
								  where x.UserID == memberID && x.GroupID == groupID
								  select x).SingleOrDefault();

            //If the user is found we remove him
			if (myUser != null)
			{
				db.UserToGroups.DeleteOnSubmit(myUser);
				db.SubmitChanges();
			}
        }
        #endregion
    }
}